import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { pa } from 'element-plus/es/locale/index.mjs'

// 公共路由
const publicRoutes = [
  {
    path: '/',
    name: 'Login',
    component: () => import('@/views/LoginView.vue'),
    meta: {
      layout: 'empty', // 必须显式设置
      title: '系统登录',
      requiresAuth: false

    }
  },
  {
    path: '/404',
    name: '404',
    component: () => import('@/views/404.vue'),
    meta: { title: '404', hidden: true }
  }
]

// 动态路由（需要权限）
const asyncRoutes = [
  {
    path: '/',
    name:"MainLayout",
    component:()=>import('@/layouts/MainLayout.vue'),
    meta: { requiresAuth: true },
   
    children: [
     
     
    ]
  },{
    path: '/MainLayout',  
    name: 'MainLayout',
    component: () => import('@/layouts/MainLayout.vue'),
    meta: { 
      requiresAuth: true,
      screenMode: true 
    },
  },
  {
    path: '/overview',
    name: 'Overview',
    component: () => import('@/views/OverviewView.vue'),
    meta: { 
        requiresAuth: true,
        screenMode: true 
      },
  },
  {
    path: '/access',
    name: 'Access',
    component: () => import('@/views/AccessView.vue'),
    meta: { 
      requiresAuth: true,
      screenMode: true 
    },
  },
  {
    path: '/security',
    name: 'security',
    component: () => import('@/views/SecurityView.vue'),  
    meta: { 
      requiresAuth: true,
      screenMode: true 
    },
  },
  {
    path: '/property',
    name: 'Property',
    component: () => import('@/views/PropertyView.vue'),
    meta: { 
      requiresAuth: true,
      screenMode: true 
    },
  },
  {
    path: '/control',
    name: 'Control',
    component: () => import(/* webpackChunkName: "control" */ '@/views/ControlView.vue'),
    meta: { 
      requiresAuth: true,
      screenMode: true 
    },
  },
  {
    path:'/systemguide',
    name:'systemguide',
    component:()=>import('@/views/SystemGuideView.vue'),
    meta:{
      requiresAuth:true,
      
    }
  },
  // 大屏模AA式独立路由
  {
    path: '/screen',
    meta: { 
      requiresAuth: true,
      screenMode: true 
    },
    component: () => import('@/layouts/ScreenLayout.vue'),
    children: [
      {
        path: 'overview',
        name: 'ScreenOverview',
        component: () => import('@/views/screen/OverviewView.vue'),
        meta: { title: '总览大屏' }
      },
      {
        path: 'security',
        name: 'ScreenSecurity',
        component: () => import('@/views/screen/SecurityView.vue'),
        meta: { title: '安防大屏' }
      }
    ]
  } 
]

const router = createRouter({
  history: createWebHistory(),
  routes: [
    ...publicRoutes,
    ...asyncRoutes,
  ]
})

// 修改权限验证函数
function hasPermission(roles = [], route) {
  if (!route.meta?.roles) return true
  return roles.some(role => route.meta.roles.includes(role))
}

// 动态添加路由
export function addRoutes() {
  const userStore = useUserStore()
  const accessedRoutes = filterAsyncRoutes(asyncRoutes, userStore.roles)
  accessedRoutes.forEach(route => {
    router.addRoute(route)
  })
}

// 修正后的路由守卫逻辑
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  console.log('用户认证状态:', userStore.isAuthenticated)
  console.log('当前路由需要认证:', to.meta.requiresAuth)

  if (to.meta.requiresAuth && !userStore.isAuthenticated) {
    return next('/')
  }

  next()
})

// 过滤异步路由
function filterAsyncRoutes(routes, roles) {
  const res = []
  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })
  return res
}

// 导出动态路由加载方法
export const addDynamicRoutes = (userType) => {
  const routes = []
  
  // 管理员路由
  if (userType === 'admin') {
    // routes.push({
    //   path: '/MainLayout',
    //   component: () => import('@/layouts/MainLayout.vue'),
    //   meta: { requiresAuth: true }
    // })
  }

  // 普通用户路由
  routes.push({
    path: '/',
    component: () => import('@/views/LoginView.vue'),
    meta: { requiresAuth: true }
  })

  // 添加路由
  routes.forEach(route => {
    if (!router.hasRoute(route.path)) {
      router.addRoute(route)
    }
  })
}

export default router

export { asyncRoutes } 